iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 1
0
自我挑戰組

iOS 筆記系列 第 1

initWithFrame:、initWithCoder:、awakeFromNib 的差別

  • 分享至 

  • xImage
  •  

initWithFrame:

初始化並且回傳一個指定長寬的新 view 物件

- (instancetype)initWithFrame:(CGRect)frame {
	self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}

只有使用程式初始化物件時才會呼叫此方法,如果是用 Interface Builder 建立的物件呼叫的是 initWithCoder:

  • The new view object must be inserted into the view hierarchy of a window before it can be used.

initWithCoder:

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        
    }
    return self;
}

If you have an advanced need that requires substituting a different object after decoding, you can do so in awakeAfterUsingCoder:

awakeFromNib

Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib file.

- (void)awakeFromNib {
    [super awakeFromNib];
    
}

蘋果官方的文件:

During the instantiation process, each object in the archive is unarchived and then initialized with the method befitting its type. Objects that conform to the NSCoding protocol are initialized using their initWithCoder: method. All objects that do not conform to the NSCoding protocol are initialized using their init method. After all objects have been instantiated and initialized, the nib-loading code reestablishes the outlet and action connections for all of those objects. It then calls the awakeFromNib method of the objects.

Typically, you implement awakeFromNib for objects that require additional set up that cannot be done at design time. For example, you might use this method to customize the default configuration of any controls to match user preferences or the values in other controls. You might also use it to restore individual controls to some previous state of your application.

歸納幾點:

  • 這個方法不是用來初始化物件的
  • 這個方法是在被初始化後被呼叫,所以只會執行一次
  • 只有用 nib 建立的物件才會呼叫這個方法
  • 通常會在這個方法裡面寫一些沒辦法在 Interface Builder 裡面完成的設計,或是一些因應不同情況會有不同參數的 attribute

下一篇
initWithNibName、loadNibName:owner:options: 的差別
系列文
iOS 筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言